<template>
  <div class="condition-drawer">
    <el-drawer
      v-model="conditionDrawer"
      :append-to-body="true"
      :show-close="false"
      direction="rtl"
      size="550px"
    >
      <template #header>
        <div>
          <input
            v-if="isInput"
            v-model="conditionConfig.nodeName"
            type="text"
            placeholder="条件设置"
            @blur="isInput=false"
          >
          <el-link v-else @click.stop="isInput=true">
            <el-icon class="m-icon"><i-ep-edit-pen /></el-icon>
            {{ conditionConfig && conditionConfig.nodeName }}
          </el-link>
        </div>
        <el-select v-if="conditionsConfig" v-model="conditionConfig.priorityLevel">
          <el-option
            v-for="item in conditionsConfig.conditionNodes.length"
            :key="item"
            :label="'优先级'+item"
            :value="item"
          />
        </el-select>
      </template>
      <template #default>
        <div class="condition_content" @click="isInput=false">
          <div class="condition_item">
            <span class="label">发起人</span>
            <div class="ep-input">
              <div class="ep-input__wrapper" @click="userDialogVisible=true">
                <el-tag
                  v-for="(tag,index1) in conditionConfig.nodeUserList"
                  :key="index1"
                  style="margin: 3px;"
                  closable
                  effect="plain"
                  type="info"
                  @close="handleClose(tag)"
                >
                  {{ tag.name }}
                </el-tag>
                <input
                  v-if="conditionConfig.nodeUserList.length == 0"
                  class="ep-input__inner"
                  type="text"
                  readonly
                  placeholder="可指定发起人作为条件项"
                >
              </div>
            </div>
          </div>

          <div v-for="(item,index) in conditionListSort" :key="index" class="condition_item">
            <span class="label">{{ conditionOptions(item.id).label }}</span>
            <div v-if="item.type==='input' || item.type==='textarea'" class="value">
              <el-input v-model="item.value" />
            </div>

            <div v-if="item.type==='number'" class="value">
              <el-select v-model="item.optType" style="width: 100px; margin-right: 10px;">
                <el-option label="小于" value="<" />
                <el-option label="大于" value=">" />
                <el-option label="等于" value="=" />
                <el-option label="小于等于" value="<=" />
                <el-option label="大于等于" value=">=" />
              </el-select>
              <el-input-number v-model="item.value" />
            </div>

            <div v-if="item.type==='radio'" class="value">
              <el-radio-group v-model="item.value">
                <el-radio
                  v-for="(o,idx) in conditionOptions(item.id).optionItems"
                  :key="idx"
                  :label="o.value"
                >
                  {{ o.label }}
                </el-radio>
              </el-radio-group>
            </div>

            <div v-if="item.type==='checkbox'" class="value">
              <el-checkbox-group v-model="item.value">
                <el-checkbox
                  v-for="(o,idx) in conditionOptions(item.id).optionItems"
                  :key="idx"
                  :label="o.value"
                >
                  {{ o.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>

            <div v-if="item.type==='select'" class="value">
              <el-select v-model="item.value" placeholder="请选择" class="value">
                <el-option
                  v-for="(o,idx) in conditionOptions(item.id).optionItems"
                  :key="idx"
                  :label="o.label"
                  :value="o.value"
                />
              </el-select>
            </div>
          </div>
          <el-button class="condition_btn" type="primary" @click="addCondition">添加条件</el-button>
          <el-dialog v-model="conditionVisible" title="选择条件" width="480px" append-to-body>
            <div class="condition-confirm-body">
              <el-checkbox-group v-model="conditionList">
                <el-checkbox
                  v-for="(item,index) in conditions"
                  :key="index"
                  :label="item.id"
                >
                  {{ item.options.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </el-dialog>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="onCancel">取消</el-button>
          <el-button type="primary" @click="onSave">保存</el-button>
        </div>
      </template>
    </el-drawer>
    <user-dialog
      v-model="conditionConfig.nodeUserList"
      v-model:visible="userDialogVisible"
      :tree-list="treeList"
      :check-strictly="checkDept"
    />
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { useStore } from 'vuex'
import func from '../../utils/preload.js'

export default {
  props: {
    /** 审批表单条件项 */
    conditions: {
      type: Array,
      default: () => []
    },
    /** 成员列表 */
    treeList: {
      type: Array,
      default: () => []
    },
    /** 允许选中部门 */
    checkDept: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const store = useStore()
    const conditionDrawer = computed({
      get() {
        return store.state.app.workflow.conditionDrawer
      },
      set(flag) {
        store.dispatch('app/workflow/setCondition', flag)
      }
    })

    /** 编辑标题 */
    const isInput = ref(false)

    /** 条件节点 */
    const conditionsConfig = computed(() => store.state.app.workflow.conditionsConfig1.value)

    /** 当前条件 */
    const conditionConfig = computed(() => {
      const priorityLevel = store.state.app.workflow.conditionsConfig1.priorityLevel
      if (priorityLevel) {
        return conditionsConfig.value.conditionNodes[priorityLevel - 1]
      }
      return { nodeUserList: [], conditionList: [] }
    })

    /** 条件项排序显示 */
    const conditionListSort = computed(() => {
      const list = conditionConfig.value.conditionList || []
      return list.sort((a, b) => a.index - b.index)
    })

    /** 条件项options */
    const conditionOptions = (id) => {
      const field = props.conditions.find(p => p.id === id) || {}
      return field.options || {}
    }

    /** 选择成员弹窗 */
    const userDialogVisible = ref(false)

    /** 删除指定发起人 */
    const handleClose = (tag) => {
      conditionConfig.value.nodeUserList.splice(conditionConfig.value.nodeUserList.indexOf(tag), 1)
    }

    /** 条件相关 */
    const conditionVisible = ref(false)
    const conditionList = ref([])

    /** 初始化已有条件 */
    watch(conditionDrawer, (show) => {
      if (show) {
        const ids = conditionConfig.value.conditionList
          .filter(x => props.conditions.find(m => m.id === x.id))
          .map(m => m.id)
        conditionList.value = ids
        console.log('props.conditions :>> ', props.conditions)
      }
    })

    /** 监听条件变化 */
    watch(conditionList, (ids) => {
      // 移除条件项
      const remove = conditionConfig.value.conditionList.filter(p => !ids.includes(p.id))
      remove.forEach(v => {
        conditionConfig.value.conditionList.splice(conditionConfig.value.conditionList.indexOf(v), 1)
      })

      // 添加条件项
      const add = ids.filter(id => !conditionConfig.value.conditionList.find(f => f.id === id))
      add.forEach(v => {
        const item = props.conditions.find(p => p.id === v)
        const index = props.conditions.indexOf(item)
        const { id, type, name, options } = item

        if (id && type && options) {
          const opt = {
            id, index, type, name: options.name, label: options.label, value: ''
          }
          if (type === 'input' && options.type === 'number') { // 输入框数字类型
            Object.assign(opt, { type: 'number', value: 3, optType: '<' })
          } else if (type === 'number') {
            Object.assign(opt, { value: 3, optType: '<' })
          } else if (type === 'radio' || type === 'checkbox' || type === 'select') {
            Object.assign(opt, { value: options.defaultValue, optionItems: options.optionItems })
          }
          conditionConfig.value.conditionList.push(opt)
        }
      })
    })

    /** 添加条件 */
    const addCondition = () => {
      conditionVisible.value = true
    }

    /** 保存 */
    const onSave = () => {
      /** 修改优先级排序 */
      const config_level = store.state.app.workflow.conditionsConfig1.priorityLevel
      const level = conditionConfig.value.priorityLevel
      if (config_level !== level) {
        var a = conditionsConfig.value.conditionNodes.splice(config_level - 1, 1)// 截取旧下标
        conditionsConfig.value.conditionNodes.splice(level - 1, 0, a[0])// 填充新下标

        conditionsConfig.value.conditionNodes.map((item, index) => {
          item.priorityLevel = index + 1
        })
      }
      for (var i = 0; i < conditionsConfig.value.conditionNodes.length; i++) {
        conditionsConfig.value.conditionNodes[i].error = func.conditionStr(conditionsConfig.value, i) === '请设置条件' && i !== conditionsConfig.value.conditionNodes.length - 1
      }

      store.dispatch('app/workflow/setConditionsConfig', {
        value: conditionsConfig,
        flag: true,
        id: store.state.app.workflow.conditionsConfig1.id
      })
      onCancel()
    }

    /** 取消 */
    const onCancel = () => {
      store.dispatch('app/workflow/setCondition', false)
    }

    return {
      conditionDrawer,
      isInput,
      conditionsConfig,
      conditionConfig,
      conditionListSort,
      conditionOptions,
      conditionVisible,
      conditionList,
      userDialogVisible,
      handleClose,
      addCondition,
      onSave,
      onCancel
    }
  }
}
</script>

<style lang="scss" scoped>
  .condition_item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .label {
      width: 100px;
      font-size: 14px;
      color: var(--ep-color-info-dark-2);
    }
    .value {
      width: 100%;
    }

    .ep-input__wrapper {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      align-items: center;
    }
  }
  .condition_btn {
    margin-top: 20px;
  }

</style>
